package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"strconv"
	"time"
	. "xm_shop/database"
	. "xm_shop/models"
)

type GoodsCateController struct{}

// 获取所有的顶级分类
func (g GoodsCateController) GetAllTopCate(context *gin.Context) {
	var goodsCateList []GoodsCate
	DB.Where("pid = ?", 0).Find(&goodsCateList)
	context.JSON(http.StatusOK, gin.H{
		"goodsCateList": goodsCateList,
	})
}

// 获取所有分类(顶级分类 + 次级分类)
func (g GoodsCateController) Index(context *gin.Context) {
	var goodsCateList []GoodsCate
	DB.Where("pid = ?", 0).Preload("GoodsCateItems").Find(&goodsCateList)
	context.JSON(http.StatusOK, gin.H{
		"success":       true,
		"goodsCateList": goodsCateList,
	})
}

// 新增分类
func (g GoodsCateController) Add(context *gin.Context) {
	title := context.PostForm("title")
	pid, err1 := strconv.Atoi(context.PostForm("pid"))
	link := context.PostForm("link")
	template := context.PostForm("template")
	subTitle := context.PostForm("sub_title")
	keyWords := context.PostForm("key_words")
	description := context.PostForm("description")
	sort, err2 := strconv.Atoi(context.PostForm("sort"))
	status, err3 := strconv.Atoi(context.PostForm("status"))
	if err1 != nil || err2 != nil || err3 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 获取上传的图片
	file, err4 := context.FormFile("cate_img")
	if err4 != nil {
		context.String(http.StatusBadRequest, "图片上传失败")
		return
	}
	// 获取文件后缀
	extName := path.Ext(file.Filename)
	// 创建合法后缀map
	allowExtMap := map[string]bool{
		".jpeg": true,
		".jpg":  true,
		".png":  true,
		".gif":  true,
	}
	// 判断文件后缀是否合法
	if _, ok := allowExtMap[extName]; !ok {
		context.String(http.StatusBadRequest, "文件不合法")
		return
	}
	// 获取当前时间
	day := time.Now().Format("20060102")
	// 指定文件存储目录
	dir := "./static/upload/" + day
	// 递归创建目录
	os.MkdirAll(dir, 0666)
	// 获取当前时间的时间戳 + 后缀 形成文件名
	fileName := strconv.FormatInt(time.Now().Unix(), 10) + extName
	// 指定文件存储路径
	dst := path.Join(dir, fileName)
	// 保存图片文件
	err5 := context.SaveUploadedFile(file, dst)
	if err5 != nil {
		context.String(http.StatusBadRequest, "文件保存失败")
		return
	}
	// 创建记录
	goodsCate := GoodsCate{
		Title:       title,
		CateImg:     dst,
		Link:        link,
		Template:    template,
		Pid:         pid,
		SubTitle:    subTitle,
		Description: description,
		Sort:        sort,
		Status:      status,
		KeyWords:    keyWords,
		AddTime:     int(time.Now().Unix()),
	}
	if err6 := DB.Create(&goodsCate).Error; err6 != nil {
		context.String(http.StatusBadRequest, "图片保存失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success":   true,
		"goodsCate": goodsCate,
	})
}

// 编辑商品分类
func (g GoodsCateController) Edit(context *gin.Context) {
	id, err6 := strconv.Atoi(context.Param("id"))
	title := context.PostForm("title")
	pid, err1 := strconv.Atoi(context.PostForm("pid"))
	link := context.PostForm("link")
	template := context.PostForm("template")
	subTitle := context.PostForm("sub_title")
	keyWords := context.PostForm("key_words")
	description := context.PostForm("description")
	sort, err2 := strconv.Atoi(context.PostForm("sort"))
	status, err3 := strconv.Atoi(context.PostForm("status"))
	if err1 != nil || err2 != nil || err3 != nil || err6 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 检索数据
	var goodsCate GoodsCate
	DB.Where("id = ?", id).Take(&goodsCate)
	if goodsCate.ID == 0 {
		context.String(http.StatusBadRequest, "记录不存在")
		return
	}
	// 获取上传的图片
	file, err4 := context.FormFile("cate_img")
	if err4 != nil {
		context.String(http.StatusBadRequest, "图片上传失败")
		return
	}
	// 获取文件后缀
	extName := path.Ext(file.Filename)
	// 创建合法后缀map
	allowExtMap := map[string]bool{
		".jpeg": true,
		".jpg":  true,
		".png":  true,
		".gif":  true,
	}
	// 判断文件后缀是否合法
	if _, ok := allowExtMap[extName]; !ok {
		context.String(http.StatusBadRequest, "文件不合法")
		return
	}
	// 获取当前时间
	day := time.Now().Format("20060102")
	// 指定文件存储目录
	dir := "./static/upload/" + day
	// 递归创建目录
	os.MkdirAll(dir, 0666)
	// 获取当前时间的时间戳 + 后缀 形成文件名
	fileName := strconv.FormatInt(time.Now().Unix(), 10) + extName
	// 指定文件存储路径
	dst := path.Join(dir, fileName)
	// 保存图片文件
	err5 := context.SaveUploadedFile(file, dst)
	if err5 != nil {
		context.String(http.StatusBadRequest, "文件保存失败")
		return
	}
	goodsCate.Title = title
	goodsCate.CateImg = dst
	goodsCate.Link = link
	goodsCate.Template = template
	goodsCate.Pid = pid
	goodsCate.SubTitle = subTitle
	goodsCate.KeyWords = keyWords
	goodsCate.Description = description
	goodsCate.Sort = sort
	goodsCate.Status = status
	if err7 := DB.Save(&goodsCate).Error; err7 != nil {
		context.String(http.StatusBadRequest, "修改失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success":   true,
		"goodsCate": goodsCate,
	})
}

// 删除商品分类
func (g GoodsCateController) Delete(context *gin.Context) {
	id, err1 := strconv.Atoi(context.Param("id"))
	if err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 检索对应的记录
	var goodsCate GoodsCate
	DB.Where("id = ?", id).Take(&goodsCate)
	if goodsCate.ID == 0 {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 判断如果是顶级分类
	if goodsCate.Pid == 0 {
		// 判断是否存在次级分类
		var goodsCateList []GoodsCate
		DB.Where("pid = ?", goodsCate.ID).Find(&goodsCateList)
		if len(goodsCateList) > 0 {
			context.String(http.StatusBadRequest, "存在次级分类, 无法删除")
			return
		}
	}
	// 删除对应的记录
	if err2 := DB.Delete(&goodsCate).Error; err2 != nil {
		context.String(http.StatusBadRequest, "删除失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}
